#include "pm_uart3.h"

// 校验 
// 校验正确--0xff 校验错误--0x00
uint8_t CheckSum(uint8_t *data) {
    uint8_t i = 0, result = 0;
    uint16_t sum = 0;
    
    if( (data[0] == 0x42) && (data[1] == 0x4d) )
    {
        for(i = 0; i < 30; i++)
        {
            sum += data[i];
        }
        if( sum == ((data[30]<<8) + data[31]) )
        {
            result = 0xff;
        }
    }
    return result;
}
// PM 初始化
void PM_Init(void) {
    Sys_Usart3Init(9600);
    
    Power_PM(1);
    Delay_ms(20);
}

void PM_ReqGetData(uint8_t cmd) {
    uint16_t sum = 0;
    uint8_t  data[20] = {0};
    uint8_t  i = 0;
    
    data[0] = 0x42;
    data[1] = 0x4d;
    
    data[2] = cmd;
    
    data[3] = 0x00;
    data[4] = 0x00;

    for(i = 0; i < 5; i++)
    {
        sum += data[i];
    }
    data[5] = (uint8_t)(sum>>8);
    data[6] = (uint8_t)(sum>>0);
    
    Sys_Usart3SendData(data, 7);
}

void PM_GetProtocol(void) {
    Sys_Usart3RecComplete();
    if(Usart3ReadFlag&0x8000)
	{
        if( CheckSum(Usart3ReadBuf) == 0xff)
        {
            AirQuality.PM1_0 = (uint16_t)(Usart3ReadBuf[4]<<8) + (uint16_t)(Usart3ReadBuf[5]<<0);
            AirQuality.PM2_5 = (uint16_t)(Usart3ReadBuf[6]<<8) + (uint16_t)(Usart3ReadBuf[7]<<0);
            AirQuality.PM10  = (uint16_t)(Usart3ReadBuf[8]<<8) + (uint16_t)(Usart3ReadBuf[9]<<0);
        }
		Usart3ReadFlag = 0;
		memset((void *)Usart3ReadBuf,0,sizeof(Usart3ReadBuf));
	}  
    
    if(AirQuality.GetTime >= 2000)
    {
        PM_ReqGetData(0xe2);
        
        AirQuality.GetTime = 0;
    }
}




















